//
//  CustomMoviePlayerViewController.m
//
//  Copyright iOSDeveloperTips.com All rights reserved.
//

#import "CustomMoviePlayerViewController.h"
#import "CmnMacro.h"
#import "MoviePlaybackCache.h"

#if (defined(TARGET_OS_EMBEDDED) && (TARGET_OS_EMBEDDED != 0)) || (defined(TARGET_OS_IPHONE) && (TARGET_OS_IPHONE != 0)) || (defined(MAC_OS_X_VERSION_MIN_REQUIRED) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
#include <objc/runtime.h>
#else
#include <objc/objc-runtime.h>
#endif

#pragma mark -
#pragma mark Compiler Directives & Static Variables

@implementation CustomMoviePlayerViewController

// for leave fullscreen
//		[[NSNotificationCenter defaultCenter] addObserver:self
//												 selector:@selector(movieDidExitFullscreen:)
//													 name:MPMoviePlayerPlaybackDidFinishNotification
//												   object:[moviePlayer moviePlayer]];

/*---------------------------------------------------------------------------
 *  
 *--------------------------------------------------------------------------*/

#define MPAVControllerTimeDidJumpNotification @"MPAVControllerTimeDidJumpNotification"

@synthesize playBackCacheURL;
@synthesize bCachePlaybackTime;

- (void)initPlay
{
	if (!bInitPlay)
	{
		bInitPlay = YES;
		
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(handleWillResignActive:) 
													 name:UIApplicationWillResignActiveNotification
												   object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(handleDidBecomeActive:) 
													 name:UIApplicationDidBecomeActiveNotification
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(handleDidFinish:)
													 name:MPMoviePlayerPlaybackDidFinishNotification
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(handlePlaybackStateDidChange:)
													 name:MPMoviePlayerPlaybackStateDidChangeNotification
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(handleLoadStateDidChange:)
													 name:MPMoviePlayerLoadStateDidChangeNotification
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(handleDurationAvailable:)
													 name:MPMovieDurationAvailableNotification
												   object:nil];
	}
	
	[[NSNotificationCenter defaultCenter] postNotificationName: MPMoviePlayerStartNotification object: self];
	
	[[self moviePlayer] setUseApplicationAudioSession:NO];

}

- (id)initWithContentURL:(NSURL *)contentURL
{
	bInitPlay = NO;
	bCachePlaybackTime = YES;
	
	self = [super initWithContentURL:contentURL];

	[self initPlay];
	
	bPortraitLimited = NO;
	
	return self;
}

- (void)setContentURL:(NSURL *)contentURL
{
	[self.moviePlayer stop];
	
	[self.moviePlayer setContentURL:contentURL];
	
	[self initPlay];

	[self.moviePlayer play];
}

- (void)setPortraitLimited:(BOOL)bLimit
{
	bPortraitLimited = bLimit;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
{
	[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
	
	CGPoint point = CGPointMake(0, 0);
	
	if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation))
		point = CGPointMake([UIScreen mainScreen].bounds.size.height / 2, [UIScreen mainScreen].bounds.size.width / 2);
	else
		point = CGPointMake([UIScreen mainScreen].bounds.size.width / 2, [UIScreen mainScreen].bounds.size.height / 2);
	
	aiview.center = point;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
	BOOL bRet = NO;
	if (bPortraitLimited)
	{
		if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation))
			bRet = YES;
	}
	else
	{
		bRet = YES;
	}
	return bRet;
}

- (void)viewDidLoad
{
	[super viewDidLoad];

//	if (!aiview)
//	{
//		aiview = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//
//		[self.view addSubview:aiview];
//		
//		aiview.center = [self moviePlayer].view.center;
//	}
//
//	[aiview startAnimating];
}

- (void)cachePlaybackTimeFunc:(NSTimeInterval)currentPlaybackTime
{
	if (!self.playBackCacheURL)
		self.playBackCacheURL = [[self moviePlayer] contentURL];
	
	//NSLog(@"current time %f duration %f", [[self moviePlayer] currentPlaybackTime], [[self moviePlayer] duration]);
	
	if (self.bCachePlaybackTime)
	{
		if (currentPlaybackTime == 0.0 || currentPlaybackTime == [[self moviePlayer] duration])
		{
			[[MoviePlaybackCache sharedMoviePlaybackCache] removeCache:self.playBackCacheURL];
		}
		else
		{
			[[MoviePlaybackCache sharedMoviePlaybackCache] cachePlaybackTime:currentPlaybackTime withURL:self.playBackCacheURL];
		}
	}
}

- (void)cachePlaybackTime
{
	[self cachePlaybackTimeFunc:[self moviePlayer].currentPlaybackTime];
}

- (void)handleDidFinish:(NSNotification *)notification
{
	//[[NSNotificationCenter defaultCenter] removeObserver:self name:MPAVControllerTimeDidJumpNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieDurationAvailableNotification object:nil];
	
	bInitPlay = NO;

	NSDictionary * userInfo = notification.userInfo; 
	int reason = [[userInfo valueForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
	NSLog( @"finish reason %d ", reason );
	
	[[self moviePlayer] pause];
	
	//[self moviePlayer].initialPlaybackTime = -1; 
	
	//[[self moviePlayer] stop];
	
	if (cachePlaybackTimer)
	{
		[self cachePlaybackTimeFunc:(reason == MPMovieFinishReasonPlaybackEnded ? 0.0 : [self moviePlayer].currentPlaybackTime)];
		[cachePlaybackTimer invalidate];
		cachePlaybackTimer = nil;
	}
	
	[[NSNotificationCenter defaultCenter] postNotificationName: MPMoviePlayerEndNotification object:self userInfo:userInfo];
}

- (void)handlePlaybackStateDidChange:(NSNotification *)notification
{
	NSLog(@"Playback State : %d; load State : %d", [self moviePlayer].playbackState, [self moviePlayer].loadState);
	
//	if ([self moviePlayer].playbackState == MPMoviePlaybackStatePlaying && [self moviePlayer].loadState == MPMovieLoadStateUnknown)
//		self.moviePlayer.controlStyle = MPMovieControlStyleNone;
	
	[[NSNotificationCenter defaultCenter] postNotificationName:MPMoviePlayerPlayBackStateChangedNotification object:self];

	//[[MoviePlay instance] playbackStateChanged:[self moviePlayer].playbackState];
}

- (void)handleLoadStateDidChange:(NSNotification *)notification
{
	NSLog(@"Load State : %d", [self moviePlayer].loadState);
	
	//[[MoviePlay instance] loadStateChanged:[self moviePlayer].loadState];
	
	if ([self moviePlayer].loadState & MPMovieLoadStatePlayable)
	{
		[aiview stopAnimating];
		//self.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
		
		if (playbackTimeCurrent > 0.0 && playbackTimeCurrent < [self moviePlayer].duration)
		{
			[self moviePlayer].currentPlaybackTime = playbackTimeCurrent;
			playbackTimeCurrent = 0.0;
		}
	}
}

- (void)handleDurationAvailable:(NSNotification *)notification
{
	NSTimeInterval dur = [self moviePlayer].duration;
    NSLog(@"duration:%f",dur);

	if (!self.playBackCacheURL)
		self.playBackCacheURL = [[self moviePlayer] contentURL];
	
	if (self.bCachePlaybackTime)
	{
		playbackTimeCurrent = [[MoviePlaybackCache sharedMoviePlaybackCache] cachedPlaybackTimeWithURL:self.playBackCacheURL];
	}

	cachePlaybackTimer = [NSTimer scheduledTimerWithTimeInterval:3.0
														  target:self
														selector:@selector(cachePlaybackTime)
														userInfo:nil
														 repeats:YES];
}

- (void)handleWillResignActive:(NSNotification *)notification
{
	
}

- (void)handleDidBecomeActive:(NSNotification *)notification
{
	
}

- (void)dealloc 
{
	SAFE_RELEASE(aiview);
	SAFE_RELEASE(playBackCacheURL);
	
	[super dealloc];
}

- (UIView *)getControlOverlayView
{
	id internal;
	object_getInstanceVariable( self, "_internal", (void*)&internal);
	id videoViewController;
	object_getInstanceVariable(internal, "_videoViewController", (void*)&videoViewController);
	id overlayView;
	object_getInstanceVariable(videoViewController, "_overlayView", (void*)&overlayView);

	if ([overlayView isKindOfClass:[UIView class]])
		return overlayView;
	
	return nil;
}

// private function for iOS4.3
- (void)_moviePlayerViewController_applicationDidEnterBackgroundNotification:(NSNotification *)notication
{
	// do nothing
}

@end
